# 作者: 家里蹲 吴越洋
# 2023年03月08日14时54分39秒
import sys
from socket import *
import select

server_socket=socket(AF_INET,SOCK_STREAM)
# 重用对应地址和端口
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server_socket.bind(('',3000))
server_socket.listen(10)

epoll=select.epoll()
epoll.register(sys.stdin.fileno(),select.EPOLLIN)
epoll.register(server_socket.fileno(),select.EPOLLIN)
client_dict={}

while True:
    events=epoll.poll(-1)
    for event in events:
        if event[0]==server_socket.fileno():
            client_socket,client_addr=server_socket.accept()
            epoll.register(client_socket.fileno(),select.EPOLLIN)
            #加入客户字典
            client_dict[client_socket.fileno()]=client_socket
            print(f'{client_addr}加入了聊天室')

        else:
            recv_data=client_dict[event[0]].recv(1024)
            if recv_data:
                for client in client_dict.items():
                    if client[0]!=event[0]:
                        client[1].send(recv_data)
            else:
                print(f'{client_dict[event[0]][0]}离线了')
                epoll.unregister(event[0])
                client_dict[event[0]].close()
                del client_dict[event[0]]
                break


